package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @Author
 * @Date 2024/4/27 19:52
 * @Description: 公共字段自动填充切面类
 */

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("@annotation(com.sky.annotation.AutoFill)")
    public void autofillPointcut(){}

    @Before("autofillPointcut()")
    public void doBefore(JoinPoint joinPoint)  {
        log.info("开始公共字段自动填充");
    //获取当前被拦截的方法的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill=signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();//获取当前数据库操作类型

    //获取当前方法的参数，需要注意dto,entry必须放在第一个参数
        Object[] args = joinPoint.getArgs();
        if (args.length==0||args==null){
            return;
        }

        Object entry=args[0];
        //准备填充数据
        LocalDateTime now=LocalDateTime.now();
        Long userId= BaseContext.getCurrentId();

        if(operationType==OperationType.INSERT){
            try {
                Method setCreateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setCreateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, LocalDateTime.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,LocalDateTime.class);

                setCreateTime.invoke(entry,now);
                setUpdateTime.invoke(entry,now);
                setCreateUser.invoke(entry,userId);
                setUpdateUser.invoke(entry,userId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        } else if (operationType==OperationType.UPDATE) {

            try {
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,LocalDateTime.class);

                setUpdateTime.invoke(entry,now);
                setUpdateUser.invoke(entry,userId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
